package com.weshare.flink;


import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class StreamWordCount {

    public static void main(String[] args) throws Exception {

        // 创建流处理的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // StreamExecutionEnvironment.createLocalEnvironment(1)
        // StreamExecutionEnvironment.createRemoteEnvironment()
        // 设置线程的并行度
        //env.setParallelism(1);
        // 从文件中读取数据
//        String inputPath = "D:\\idea-workspace\\flink\\src\\main\\resources\\hello.txt";
//        DataStream<String> inputDataStream = env.readTextFile(inputPath);

        ParameterTool parameterTool = ParameterTool.fromArgs(args);
        String host = parameterTool.get("host");
        int port = parameterTool.getInt("port");

        // 从Socket 文本流读取数据
        DataStream<String> inputDataStream = env.socketTextStream(host, port);

        // 基于数据流进行转化运算
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = inputDataStream.flatMap(new WorldCount.MyFlatMapper())
                .keyBy(0)
                .sum(1).setParallelism(2);
        sum.print().setParallelism(1);
        // 执行
        env.execute();
    }
}
